package net.loyin.utils.encrypt;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.Key;

/**
 * Created by loyin on 15/12/24.
 */
public class DESUtils {
    private static Key key;
    public static final DESUtils me=new DESUtils();
    public DESUtils() {
        this.setkey("fdsalilfk");
    }

    public DESUtils(String keyStr) {
        this.setkey(keyStr);
    }

    private void setkey(String keyStr) {
        try {
            DESKeySpec e = new DESKeySpec(keyStr.getBytes("UTF-8"));
            SecretKeyFactory objKeyFactory = SecretKeyFactory.getInstance("DES");
            key = objKeyFactory.generateSecret(e);
        } catch (Exception var4) {
            throw new RuntimeException(var4);
        }
    }

    public final String encryptString(String str) {
        byte[] bytes = str.getBytes();

        try {
            Cipher e = Cipher.getInstance("DES");
            e.init(1, key);
            byte[] encryptStrBytes = e.doFinal(bytes);
            return new String(Base64.encodeBase64(encryptStrBytes), "UTF-8");
        } catch (Exception var5) {
            throw new RuntimeException(var5);
        }
    }

    public final String decryptString(String str) {
        try {
            byte[] e = Base64.decodeBase64(str.getBytes("UTF-8"));
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(2, key);
            e = cipher.doFinal(e);
            return new String(e);
        } catch (Exception var4) {
            throw new RuntimeException();
        }
    }

    public static void main(String[] args) {
        DESUtils des = new DESUtils();
        String test = des.encryptString("123456");
        System.out.println(test);
        System.out.println(des.decryptString(test));
    }
}
